<template>
  <div class="flex flex-col fixed top-0 left-0 right-0 bottom-0 bg-[#000000]">
    <van-tabs background="#000">
      <van-tab v-for="(item, index) in toolsObjList">
        <template #title>
          <img
            class="w-4 h-4"
            :src="item.src"
            alt=""
            @click="cornerstoneToolsSelect(item.toolsname, index)"
          />
        </template>
      </van-tab>
      <van-tab>
        <template #title>
          <img
            @click="isSelectWindow = true"
            class="w-4 h-4"
            :src="getImg('window.png')"
            alt=""
          />
        </template>
        <div
          class="flex text-base gap-3 bg-[#202023] p-1 rounded-sm text-[#fff] absolute w-full"
        >
          <div
          class="cursor-pointer"
            @click="handleSelectWindow(item.name)"
            v-for="(item, index) in selectWindowList"
            :key="index"
          >
            {{ item.name }}
          </div>
        </div>
      </van-tab>
    </van-tabs>
    <div class="flex-1">
      <div class="w-full h-full">
        <div id="test" class="w-full h-full"></div>
      </div>
    </div>
    <div
      class="gap-1 fixed z-20 top-7 duration-100"
      :class="{ 'translate-x-[-70px]': !isShowGroup }"
    >
      <div
        class="w-[50px] h-[70px]"
        v-for="(item, index) in group"
        :key="index"
      >
        <!-- mask -->
        <div
          class="w-[50px] h-[60px] absolute z-100 p-1 rounded-sm"
          :class="{ 'border-[#202023] border-4': index === currentViewIndex }"
          @click="choose(item, index)"
        ></div>
        <div class="viewport h-full w-full"></div>
      </div>
      <div
        class="absolute right-[-50px] top-0 z-30 text-zinc-300"
        @click="isShowGroup = !isShowGroup"
      >
        <img
          width="50"
          height="50"
          :src="
            getImg(
              !isShowGroup ? 'Right button-fill.png' : 'left-circle-fill.png'
            )
          "
          alt=""
        />
      </div>
    </div>
    <partition-window
      v-if="showpartition"
      :isSelectWindow="isSelectWindow"
      ref="partitionWindowRef"
      :partitionType="partitionType"
      :group="group"
      :cornerstoneToolsType="cornerstoneToolsType"
      :currentIndex="currentIndex"
    ></partition-window>
  </div>
</template>

<script>
// 渲染我们的图像，并提供有用的事件和方法来使响应视口变化的工具成为可能
import cornerstone from 'cornerstone-core'
// 某些工具用于辅助向量数学或其他复杂运算的依赖项
import cornerstoneMath from 'cornerstone-math'
// import cornerstoneTools from "cornerstone-tools"
import cornerstoneTools from '@/lib/cornerstoneTools'
// 触摸事件和手势的跨浏览器支持
import Hammer from 'hammerjs'
// web图片加载
import cornerstoneWebImageLoader from 'cornerstone-web-image-loader'
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader'
import dicomParser from 'dicom-parser'
import goodStorage from 'good-storage'
import $common from '@/utils/commonality.ts'
import { ImgUtil } from '@/utils/imgUtil'
import partitionWindow from './components/partitionWindow.vue'

cornerstoneTools.external.cornerstone = cornerstone
cornerstoneTools.external.Hammer = Hammer
cornerstoneTools.external.cornerstoneMath = cornerstoneMath
cornerstoneWebImageLoader.external.cornerstone = cornerstone
cornerstoneWADOImageLoader.external.cornerstone = cornerstone
cornerstoneWADOImageLoader.external.dicomParser = dicomParser
const { getImg } = ImgUtil

export default {
  name: 'editAnnotation',
  components: {
    partitionWindow
  },
  data() {
    return {
      dicomInfo: null,
      selectWindowList: [
        { name: '1x1' },
        { name: '2x1' },
        { name: '1x2' },
        { name: '2x2' }
      ],
      isShowGroup: false,
      partitionType: '',
      showpartition: false,
      currentViewIndex: 0,
      currentIndex: 0,
      cornerstoneToolsType: 'RectangleRoi',
      toolsObjList: [
        {
          src: getImg('RectangleRoi.png'),
          toolsname: 'RectangleRoi'
        },
        {
          src: getImg('ellipse.png'),
          toolsname: 'EllipticalRoi'
        },
        {
          src: getImg('custom.png'),
          toolsname: 'FreehandRoi'
        },
        {
          src: getImg('eraser.png'),
          toolsname: 'Eraser'
        },
        {
          src: getImg('pan.png'),
          toolsname: 'Pan'
        },
        {
          src: getImg('Angle.png'),
          toolsname: 'Angle'
        },
        {
          src: getImg('zoom.png'),
          toolsname: 'ZoomTouchPinch'
        },
        {
          src: getImg('length.png'),
          toolsname: 'Length'
        },
        {
          src: getImg('CircleRoi.png'),
          toolsname: 'CircleRoi'
        }
      ],

      loading: false,
      activeIndex: -1,
      group: [],
      // 中间图片标注
      imgSrc: '',
      ele: null,
      toolDatas: null,
      markeData: {},
      markeImgName: '',
      markImgId: '',
      isSelectWindow: false
    }
  },
  mounted() {
    console.log('mounted')
    this.$nextTick(() => {
      $common.labelText = ''
      $common.labelColor = '#aef344'
      this.dicomInfo = goodStorage.get('dicom')
      console.log(this.dicomInfo)
      let group = this.dicomInfo.seriesList.map((item) => {
        return {
          id: item.seriesUid,
          dataIo: 'wadouri:http://172.16.1.105:5007' + item.instanceList[0].imageId,
          dataName: item.seriesNumber,
          state: 'complete'
        }
      })
      this.imgSrc = group[0].dataIo
      this.group = group
      this.activeIndex = 0
      this.initCornerstoneTools()
      this.loadToolStates()
      this.initViewportList()
    })
  },
  methods: {
    getImg(name) {
      return getImg(name)
    },
    handleSelectWindow(partitionType) {
      this.partitionType = partitionType
      this.showpartition = false

      setTimeout(() => {
        this.showpartition = true
      }, 0)
    },
    //激活标注工具
    cornerstoneToolsSelect(type, index) {
      this.currentIndex = index
      this.isSelectWindow = false
      console.log(this.currentIndex)
      this.cornerstoneToolsType = type
      this.activeTool(this.cornerstoneToolsType)
    },

    // 选择多张标注图片
    choose(item, index) {
      this.currentViewIndex = index
      this.activeIndex = index
      this.markImgId = item.id
      this.markeImgName = item.dataName
      this.imgSrc = item.dataIo
      this.clearToolState()
      this.loadToolStates()
      this.loadWebImg(this.imgSrc)
      if (this.showpartition) {
        this.$refs.partitionWindowRef.initViewportList(
          item,
          this.currentViewIndex
        )
      }
    },
    // 组合名称改变
    changeColor(item) {
      $common.labelText = item.name
      $common.labelColor = item.color
    },
    initViewportList() {
      this.$nextTick(() => {
        const elList = document.querySelectorAll('.viewport')
        elList.forEach((el, index) => {
          cornerstone.enable(el)
          cornerstone
            .loadAndCacheImage(this.group[index].dataIo)
            .then((image) => {
              cornerstone.displayImage(el, image)
            })
        })
      })
    },
    // 初始化标注工具
    initCornerstoneTools() {
      cornerstoneTools.init({
        showSVGCursors: true
      })
      // 获取元素标签
      this.ele = document.querySelector('#test')
      cornerstone.enable(this.ele)
      // 加载图像
      this.loadWebImg(this.imgSrc)
      // 添加方形选框工具
      this.addTools()
      this.activeTool(this.cornerstoneToolsType)
      // 添加选框颜色
      cornerstoneTools.toolColors.setToolColor('#a4ed32')
    },
    // 加载图像
    loadWebImg(url) {
      console.log(url)
      console.log('图片正在加载中')
      cornerstone.loadAndCacheImage(url).then((image) => {
        cornerstone.displayImage(this.ele, image)
      })
    },
    // 添加选框工具
    addTools() {
      // 添加工具
      console.log('工具正在加载中')
      // 方形选框
      cornerstoneTools.addTool(cornerstoneTools.RectangleRoiTool, this.ele)
      // 椭圆选框
      cornerstoneTools.addTool(cornerstoneTools.EllipticalRoiTool, this.ele)
      // 自定义选框
      cornerstoneTools.addTool(cornerstoneTools.FreehandRoiTool, this.ele)
      // 橡皮擦
      cornerstoneTools.addTool(cornerstoneTools.EraserTool, this.ele)
      cornerstoneTools.addTool(cornerstoneTools.PanTool, this.ele)
      cornerstoneTools.addTool(cornerstoneTools.AngleTool, this.ele)
      cornerstoneTools.addTool(cornerstoneTools.ZoomTool, this.ele)
      cornerstoneTools.addTool(cornerstoneTools.ZoomTouchPinchTool, this.ele)
      cornerstoneTools.addTool(cornerstoneTools.LengthTool, this.ele)
      cornerstoneTools.addTool(cornerstoneTools.CircleRoiTool, this.ele)
      cornerstoneTools.addTool(cornerstoneTools.ReferenceLinesTool, this.ele)
      console.log(cornerstoneTools)
    },
    // 激活工具
    activeTool(toolName) {
      // { mouseButtonMask: 1 }  //鼠标左键点击触发
      // { mouseButtonMask: 2 }  //鼠标右键点击触发
      // { mouseButtonMask: 4 }  //鼠标滚轮键点击触发
      // 启用工具
      cornerstoneTools.setToolActive(toolName, { mouseButtonMask: 1 })
    },
    // 清除工具
    clearToolState() {
      if (!this.ele) return
      cornerstoneTools.clearToolState(this.ele, 'RectangleRoi')
      cornerstoneTools.clearToolState(this.ele, 'EllipticalRoi')
      cornerstoneTools.clearToolState(this.ele, 'FreehandRoi')
      cornerstoneTools.clearToolState(this.ele, 'Eraser')
      cornerstoneTools.clearToolState(this.ele, this.cornerstoneToolsType)
      cornerstone.updateImage(this.ele)
    },
    // 保存工具状态
    saveToolData() {
      let data = cornerstoneTools.getToolState(
        this.ele,
        this.cornerstoneToolsType
      )
        ? JSON.parse(
            JSON.stringify(
              cornerstoneTools.getToolState(this.ele, this.cornerstoneToolsType)
                .data
            )
          )
        : null
      if (!data) return
      this.markeData[this.group[this.activeIndex].id] = data
    },
    // 加载工具状态
    loadToolStates() {
      const toolDatas = this.markeData[this.group[this.activeIndex].id]
      // const toolDatas = this.markeData[[this.markeImgName]]
      if (!toolDatas) return

      setTimeout(() => {
        toolDatas.forEach((data) => {
          cornerstoneTools.addToolState(
            this.ele,
            this.cornerstoneToolsType,
            data
          )
        })
        cornerstone.updateImage(this.ele)
      }, 300)
    }
  },
  beforeDestroy() {
    console.log('beforeDestroy')
    this.clearToolState()
  }
}
</script>
